
using BookApp.Domain;
using BookApp.Dto;
using BookApp.Repository;
using Microsoft.AspNetCore.Mvc;

namespace BookApp.Controllers;

[ApiController]
[Route("api/[controller]")]
public class BookController : ControllerBase
{
    private readonly IRepository<Book> _bookRep;
    public BookController(IRepository<Book> bookRep)
    {
        _bookRep = bookRep;
    }
    [HttpGet]
    public async Task<IActionResult> Get()
    {
        var list = await _bookRep.GetAllAsync();
        return Ok(new { Code = 1000, Msg = "获取列表成功", Data = list });
    }
    [HttpPost]
    public async Task<IActionResult> Post(BookCreateDto bookCreateDto)
    {
        var book = new Book { BookName = bookCreateDto.BookName, Author = bookCreateDto.Author };
        await _bookRep.CreateAsync(book);
        return Ok(new { Code = 1000, Msg = "创建成功", Data = book });
    }
    [HttpPut("{id}")]
    public async Task<IActionResult> Put(int id, BookCreateDto bookCreateDto)
    {
        var book = await _bookRep.GetByIdAsync(id);
        if (book == null)
        {
            return Ok(new { Code = 1000, Msg = "修改失败", Data = "" });
        }
        book.BookName = bookCreateDto.BookName;
        book.Author = bookCreateDto.Author;
        await _bookRep.UpdateAsync(book);
        return Ok(new { Code = 1000, Msg = "修改成功", Data = book });
    }
    [HttpDelete("{id}")]
    public async Task<IActionResult> Del(int id)
    {
        var book = await _bookRep.GetByIdAsync(id);
        if (book == null)
        {
            return Ok(new { Code = 1000, Msg = "删除失败", Data = "" });
        }
        await _bookRep.DeleteAsync(book);
        return Ok(new { Code = 1000, Msg = "删除成功", Data = book });
    }
}